#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速网站访问器
使用系统已安装的浏览器，避免下载驱动

依赖：系统已安装 Chrome 或 Firefox
"""

import time
import random
import csv
import os
import subprocess
from datetime import datetime
import numpy as np

# ============= 配置区域（在这里修改参数） =================
CONFIG = {
    "URL": "https://blog.csdn.net/Zero_VPN/article/details/154238580?spm=1001.2014.3001.5501",
    "MAX_VISITS": 0,  # 设置为0表示无限循环
    "INTERVAL_MEAN": 5,
    "BROWSER": "auto",  # auto/chrome/firefox
    "HEADLESS": True,
    "CSV_FILE": "visits_log_fast.csv",
}
# ========================================================

def check_browser():
    """检查系统可用的浏览器"""
    browsers = {
        "chrome": ["google-chrome-stable", "google-chrome", "chromium-browser", "chromium"],
        "firefox": ["firefox", "firefox-esr"]
    }
    
    for browser_name, commands in browsers.items():
        for cmd in commands:
            try:
                result = subprocess.run(["which", cmd], capture_output=True, text=True)
                if result.returncode == 0:
                    return browser_name, cmd
            except:
                continue
    return None, None

def get_browser_command(browser_type, browser_cmd, url, headless=True):
    """获取浏览器启动命令"""
    if browser_type == "chrome":
        cmd = [browser_cmd]
        if headless:
            cmd.extend(["--headless=new"])
        cmd.extend([
            "--no-sandbox",
            "--disable-gpu",
            "--disable-dev-shm-usage",
            "--remote-debugging-port=0",
            url
        ])
    else:  # firefox
        cmd = [browser_cmd]
        if headless:
            cmd.append("-headless")
        cmd.append(url)
    
    return cmd

def get_log_file_path():
    """获取日志文件路径"""
    script_dir = os.path.dirname(os.path.abspath(__file__))
    logs_dir = os.path.join(script_dir, "logs")
    if not os.path.exists(logs_dir):
        os.makedirs(logs_dir)
    return os.path.join(logs_dir, CONFIG["CSV_FILE"])

def now_iso():
    """返回当前时间的 ISO 格式字符串"""
    return datetime.utcnow().isoformat() + "Z"

def get_poisson_interval(mean):
    """使用泊松分布生成访问间隔时间"""
    interval = np.random.exponential(mean)
    return max(2.0, interval)

def write_csv_header(csvfile):
    """写入 CSV 文件头"""
    with open(csvfile, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        if f.tell() == 0:
            writer.writerow([
                "timestamp_utc", 
                "visit_number", 
                "url", 
                "browser",
                "status", 
                "note"
            ])

def log_visit(visit_num, url, browser, status, note=""):
    """记录访问日志到 CSV"""
    log_file = get_log_file_path()
    with open(log_file, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow([
            now_iso(),
            visit_num,
            url,
            browser,
            status,
            note
        ])

def visit_with_browser(url, browser_type, browser_cmd):
    """使用浏览器访问页面"""
    try:
        cmd = get_browser_command(browser_type, browser_cmd, url, CONFIG["HEADLESS"])
        
        start_time = time.time()
        # 设置超时时间为30秒
        result = subprocess.run(cmd, timeout=30, capture_output=True, text=True)
        response_time = round(time.time() - start_time, 2)
        
        if result.returncode == 0:
            return {
                'success': True,
                'response_time': response_time,
                'note': f'访问成功，耗时 {response_time} 秒'
            }
        else:
            return {
                'success': False,
                'response_time': response_time,
                'note': f'浏览器返回错误代码: {result.returncode}'
            }
            
    except subprocess.TimeoutExpired:
        return {
            'success': False,
            'response_time': 30,
            'note': '访问超时（30秒）'
        }
    except Exception as e:
        return {
            'success': False,
            'response_time': 0,
            'note': f'访问异常: {str(e)}'
        }

def main():
    """主函数"""
    print("🚀 开始快速访问任务")
    print(f"📍 目标 URL: {CONFIG['URL']}")
    print(f"🔢 最大访问次数: {CONFIG['MAX_VISITS']}")
    print(f"⏱️  平均间隔: {CONFIG['INTERVAL_MEAN']} 秒")
    
    # 检查浏览器
    browser_type, browser_cmd = check_browser()
    if not browser_type:
        print("❌ 错误：系统中未找到 Chrome 或 Firefox 浏览器")
        print("💡 请安装以下任一浏览器：")
        print("   Ubuntu/Debian: sudo apt install chromium-browser")
        print("   Firefox: sudo apt install firefox")
        return
    
    print(f"🔍 使用浏览器: {browser_type} ({browser_cmd})")
    print(f"💾 日志文件: {get_log_file_path()}")
    print("-" * 60)
    
    # 确保日志文件存在
    write_csv_header(get_log_file_path())
    
    visit_count = 0
    max_visits = CONFIG["MAX_VISITS"] if CONFIG["MAX_VISITS"] > 0 else float('inf')
    
    while visit_count < max_visits:
        visit_count += 1
        
        print(f"[访问 #{visit_count}]")
        
        # 访问页面
        result = visit_with_browser(CONFIG["URL"], browser_type, browser_cmd)
        
        if result['success']:
            status = "✅ 成功"
            print(f"  {status}")
            print(f"  📊 {result['note']}")
        else:
            status = "❌ 失败"
            print(f"  {status}")
            print(f"  💥 {result['note']}")
        
        # 记录日志
        log_visit(
            visit_count, 
            CONFIG["URL"], 
            browser_type, 
            "成功" if result['success'] else "失败", 
            result['note']
        )
        
        # 如果不是最后一次访问，计算等待时间
        if visit_count < max_visits:
            wait_time = get_poisson_interval(CONFIG["INTERVAL_MEAN"])
            print(f"  ⏳ 等待 {wait_time:.1f} 秒后进行下一次访问...")
            time.sleep(wait_time)
        
        print()
    
    print("✅ 已完成所有访问")
    print(f"📊 总访问次数: {visit_count}")
    print(f"💾 日志已保存到: {get_log_file_path()}")

if __name__ == "__main__":
    main()